import random
import sys
import time

from selenium.webdriver import ActionChains
from libs.action import WebDriverAction
from libs.game import Game
from libs.image import ImageTool
from libs.log import Log
from libs.movement import Movement
from libs.task_helper import TaskHelper
from libs.window import AdsWindow


def go_saona():
    action.handle_dialog()
    # 检查是否在温泉中
    sona_left_flower = 'sona_left_flower.png'
    flower_loc = image_tool.find_target(sona_left_flower)
    if flower_loc is None:
        log.debug('left flower not found')
        action.goto_saona()
        action.wait_page_loaded()
        movement.keep_move_up(5)

    flower_loc = image_tool.find_target(sona_left_flower)
    flower_x, flower_y = flower_loc
    if 500 < flower_y or flower_y < 160:
        log.debug('not in sona pool')
        image_tool.move_to_match_target(sona_left_flower, None, 310, 20)
    log.debug('in sona pool')

    recovering = False
    coming_times = 0
    saona_minutes = 0
    wait_minutes = 5
    for _ in range(20):
        action.handle_dialog()
        if saona_minutes >= 70:
            log.debug('saona_more_than_one_hour, finish')
            after_saona()
            break

        game.enter_game(user_id)
        hazel_image = 'saona_right_tree.png'
        hazel_loc = image_tool.find_target(hazel_image)
        if hazel_loc is None:
            log.debug('hazel_not_found, re_enter')
            game.enter_game(user_id)
            continue

        hazel_x, hazel_y = hazel_loc
        ac.reset_actions()
        ac.move_by_offset(hazel_x -150, hazel_y + 150).perform()
        time.sleep(3)

        if is_coming_back():
            coming_times += 1
            if recovering:
                after_saona()
                break
            else:
                if coming_times == 1:
                    # 第一次发现是is coming刷新页面重试
                    log.debug(f"is_coming, refresh page")
                    driver.refresh()
                    time.sleep(10)
                    continue
                else:
                    log.info(f"not_time_for_saona, retry after {8 * 60 * 60} seconds")
                    task_helper.saona(delay_seconds=8 * 60 * 60)
                    time.sleep(10)
                    break
        elif is_recovering():
            if not recovering:
                recovering = True
                game.snapshot(user_id, 'before_sona')
                log.debug('check_every_five_minutes')
            else:
                saona_minutes += wait_minutes
                log.debug(f"recovering, sona_minutes={saona_minutes}")
            time.sleep(60 * wait_minutes)
            wait_minutes = random.randint(5, 10)
            continue
        else:
            log.debug('unknown_condition')
            saona_minutes += 1
            time.sleep(60)


def is_coming_back():
    image_tool = ImageTool(driver)
    come_back_image = 'saona_come_back_in.png'
    come_back_loc = image_tool.find_target(come_back_image)
    return come_back_loc is not None


def is_recovering():
    image_tool = ImageTool(driver)
    energy_go_go_image = 'saona_energy_to_go.png'
    energy_to_go_loc = image_tool.find_target(energy_go_go_image)
    return energy_to_go_loc is not None


def after_saona():
    game.snapshot(user_id, 'after_sona')
    log.info('saona finish')
    task_helper.saona(delay_seconds=24 * 60 * 60)

if __name__ == "__main__":
    parser = TaskHelper.default_args_parser('Saona')
    args = parser.parse_args()
    task_helper = TaskHelper.from_args(args)

    user_id = args.user_id
    log = Log(user_id)
    log.info('go_saona')
    try:
        # 启动窗口
        driver = AdsWindow(user_id).open()
        action = WebDriverAction(driver)
        movement = Movement(driver)
        ac = ActionChains(driver)
        image_tool = ImageTool(driver)
        game = Game(driver, user_id)
        # 进入游戏
        game.enter_game(user_id)
        energy = game.get_energy()
        if energy >= 700:
            # 体力超过700先去烹饪
            task_helper.saona(delay_seconds=random.randint(60 * 60, 2 * 60 * 60))
        else:
            go_saona()
        task_helper.task_success()
    except Exception as e:
        task_helper.task_fail()
        task_helper.saona(retry=True)
        raise e
